"""
Redis客户端服务
"""
import json
import redis
from typing import Optional, Dict, Any
from config.settings import settings
from utils.logger import audit_logger


class RedisClient:
    """Redis客户端封装"""
    
    def __init__(self):
        self.client = None
        self.connect()
    
    def connect(self):
        """连接Redis"""
        try:
            self.client = redis.Redis(
                host=settings.redis_host,
                port=settings.redis_port,
                password=settings.redis_password,
                db=settings.redis_db,
                decode_responses=True,
                socket_connect_timeout=5,
                socket_timeout=5,
                retry_on_timeout=True
            )
            # 测试连接
            self.client.ping()
            audit_logger.info("Redis连接成功")
        except Exception as e:
            audit_logger.error(f"Redis连接失败: {e}")
            raise
    
    def push_to_queue(self, queue_name: str, data: Dict[str, Any]) -> bool:
        """推送数据到队列"""
        try:
            json_data = json.dumps(data, ensure_ascii=False, default=str)
            result = self.client.lpush(queue_name, json_data)
            audit_logger.debug(f"推送数据到队列 {queue_name}: {data}")
            return result > 0
        except Exception as e:
            audit_logger.error(f"推送数据到队列失败: {e}")
            return False
    
    def pop_from_queue(self, queue_name: str, timeout: int = 0) -> Optional[Dict[str, Any]]:
        """从队列弹出数据"""
        try:
            # 使用阻塞式弹出，timeout=0表示永久等待
            result = self.client.brpop(queue_name, timeout=timeout)
            if result:
                _, json_data = result
                data = json.loads(json_data)
                audit_logger.debug(f"从队列 {queue_name} 弹出数据: {data}")
                return data
            return None
        except Exception as e:
            audit_logger.error(f"从队列弹出数据失败: {e}")
            return None
    
    def get_queue_length(self, queue_name: str) -> int:
        """获取队列长度"""
        try:
            return self.client.llen(queue_name)
        except Exception as e:
            audit_logger.error(f"获取队列长度失败: {e}")
            return 0
    
    def set_cache(self, key: str, value: Any, expire: int = 3600) -> bool:
        """设置缓存"""
        try:
            json_value = json.dumps(value, ensure_ascii=False, default=str)
            result = self.client.setex(key, expire, json_value)
            return result
        except Exception as e:
            audit_logger.error(f"设置缓存失败: {e}")
            return False
    
    def get_cache(self, key: str) -> Optional[Any]:
        """获取缓存"""
        try:
            json_value = self.client.get(key)
            if json_value:
                return json.loads(json_value)
            return None
        except Exception as e:
            audit_logger.error(f"获取缓存失败: {e}")
            return None
    
    def delete_cache(self, key: str) -> bool:
        """删除缓存"""
        try:
            result = self.client.delete(key)
            return result > 0
        except Exception as e:
            audit_logger.error(f"删除缓存失败: {e}")
            return False
    
    def health_check(self) -> bool:
        """健康检查"""
        try:
            self.client.ping()
            return True
        except Exception as e:
            audit_logger.error(f"Redis健康检查失败: {e}")
            return False


# 全局Redis客户端实例
redis_client = RedisClient()
